package com.ayg.test.apitest.core;

import com.ayg.test.apitest.entity.RepostJsonVo;
import com.ayg.test.apitest.entity.TestCase;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.*;
import org.testng.xml.XmlSuite;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class JsonReporterListener implements IReporter {
    private static final Logger logger = LoggerFactory.getLogger(JsonReporterListener.class);
    private static final String OUTPUT_FOLDER = "test-output/";
    private static final String FILE_NAME = "report.json";

    private StringBuilder successContent = new StringBuilder();
    private StringBuilder failContent = new StringBuilder();
    Gson gson = new Gson();

    @Override
    public void generateReport(List<XmlSuite> xmlSuites, List<ISuite> suites, String outputDirectory) {
        List<RepostJsonVo> caseList = new ArrayList<>();
        int failTestsCount = 0;
        int successTestsCount = 0;
        for (ISuite suite : suites) {
            Map<String, ISuiteResult> result = suite.getResults();

            for (ISuiteResult r : result.values()) {
                ITestContext context = r.getTestContext();
                failTestsCount = failTestsCount + context.getFailedTests().size();
                successTestsCount = successTestsCount + context.getPassedTests().size();
                IResultMap testFailed = context.getFailedTests();
                printJson(testFailed,caseList);
                IResultMap testSuccess = context.getPassedTests();
                printJson(testSuccess,caseList);
            }
        }
        Map caseExecResult = new HashMap<>();
        caseExecResult.put("reportName",xmlSuites.get(0).getName());
        caseExecResult.put("failCount",failTestsCount);
        caseExecResult.put("successCount",successTestsCount);
        caseExecResult.put("detail",caseList);
        String resultJson = gson.toJson(caseExecResult);
        System.out.println(resultJson);
        writeReportJson(resultJson);
    }

    private void printJson(IResultMap resultMap,List<RepostJsonVo> caseList) {
        Set<ITestResult> results = resultMap.getAllResults();
        for(ITestResult result1 : results){
            RepostJsonVo repostJsonVo = new RepostJsonVo();
            repostJsonVo.setStatus(result1.getStatus());
            repostJsonVo.setTime(result1.getEndMillis()-result1.getStartMillis());
            Object[] objects = result1.getParameters();
            for(Object o : objects){
                TestCase testCase  = (TestCase)o;
                repostJsonVo.setCaseName(testCase.getName());
                repostJsonVo.setApiUrl(testCase.getRequest().getUrl());
            }

            if(result1.getThrowable() != null) {
                repostJsonVo.setMessage(result1.getThrowable().getMessage());
            }
            caseList.add(repostJsonVo);
        }
    }

    private void writeReportJson(String json) {
        File reportDir= new File(OUTPUT_FOLDER);
        if(!reportDir.exists()&& !reportDir .isDirectory()){
            reportDir.mkdir();
        }
        String reportPath = reportDir.getPath()+File.separator +FILE_NAME;
        try(FileWriter fileWriter = new FileWriter(reportPath)) {
            fileWriter.write(json);
            fileWriter.flush();
        } catch (IOException e) {
            logger.error("{}",e);
        }
    }


}
